<?php
session_start();

if (!isset($_SESSION['user'])) {
    header("Location: http://localhost:8888/salesianichioggia.it/dashboard/login.php");
    die();
}
require ('../classes/HTMLManager.class.php');
$u = unserialize($_SESSION['user']);

if((!in_array(1, $u->permissions) && !in_array(4, $u->permissions))) {
    echo'Non hai il permesso di accedere a questa pagina! Contatta il webmaster per ulteriori informazioni';
    die();
}

define(ACTION_NEW, 'new');
define(ACTION_EDIT, 'edit');
define(ACTION_LIST, 'list');
define(ACTION_SAVE, 'save');
define(ACTION_DELETE, 'delete');



require ('../classes/EventManager.class.php');

if (isset($_GET['action'])){
    $em = new EventManager();
    $event = $events = null;
    if($_GET['action'] == ACTION_EDIT) { // ACTION: EDIT
        if (isset($_GET['id'])) {
            $event = $em->get_event_by_id($_GET['id']);
        }
    } else if ($_GET['action'] == ACTION_LIST) { // ACTION: LIST
        $now = null;
        if(isset($_GET['month']) && isset($_GET['year'])) {
            $events = $em->get_all_events($_GET['month'], $_GET['year']);
            $str_date = $_GET['year'].'-'.$_GET['month'].'-1';
        } else {
            $now = new DateTime('now');
            $month = $now->format('m');
            $year = $now->format('Y');
            $events = $em->get_all_events($month, $year);
            $str_date = $year.'-'.$month.'-1';
        }
        $date = new DateTime($str_date);
        $current_month = $date->format('n');
        $current_year = $date->format('Y');
        $date->add(new DateInterval("P1M"));
        $next_month = $date->format('n');
        $next_year = $date->format('Y');
        $date->sub(new DateInterval("P2M"));
        $prev_month = $date->format('n');
        $prev_year = $date->format('Y');
    } else if ($_GET['action'] == ACTION_SAVE) { // ACTION: SAVE
        $e = new Event();
        $e->start = new DateTime($_POST['start']);
        $e->end = new DateTime($_POST['end']);
        $e->title = $_POST['title'];
        $e->description = $_POST['description'];
        $e->all_day = isset($_POST['all_day']) ? TRUE : FALSE;
        $e->type_id = $_POST['type'];
        
        if (isset($_GET['id'])) { //ACTION: EDIT SAVE
            $e->id = $_GET['id'];
            $em->update_event($e);
            header("Location: http://www.salesianichioggia.it/dashboard/event.php?action=list");
            die();
        } else { // ACTION: NEW SAVE
            $em->add_event($e);
            header("Location: http://www.salesianichioggia.it/dashboard/event.php?action=list");
            die();
        }
    } else if ($_GET['action'] == ACTION_DELETE) { // ACTION: DELETE
        if (isset($_GET['id'])) {
            $em->delete_event($_GET['id']);
            header("Location: http://www.salesianichioggia.it/dashboard/event.php?action=list");
            die();
        }
    }
}

include_once ('event.view.php');
?>
